// 导入工具类
import { GiteeUtils } from '../utils/giteeUtils.js';
import { BookmarkUtils } from '../utils/bookMarkUtils.js';
import { NotificationsUtils } from '../utils/notificationsUtils.js';


// 初始化工具类实例
const giteeUtils = new GiteeUtils();
const bookmarkUtils = new BookmarkUtils();
const notificationsUtils = new NotificationsUtils();

export class SyncService {
    constructor() {
        this.repoName = '';
        this.token = '';
        this.fileName = '';
        this.loadStoredConfig();
    }

    /**
     * 从本地存储中加载配置信息
     * @returns {void} 无返回值
     */
    async loadStoredConfig() {
        await chrome.storage.local.get(['repoName', 'token', 'fileName'], (result) => {
            if (result) {
                this.repoName = result.repoName || '';
                this.token = result.token || '';
                this.fileName = result.fileName || '';
            }
        });
    }
    /** 初始远程仓库  成功true  失败false
     * 1.判断仓库是否存在 不存在则创建 
     * 2.判断文件是否存在 不存在则创建 
    **/
    async initRemoteRepo() {
        //1.判断仓库是否存在  
        const existRepo = await giteeUtils.existRepos(this.token, this.repoName);
        // 不存在则创建
        if (existRepo == 0) {
            const createRepoResult = await giteeUtils.createRepo(this.token, this.repoName);
            if ("success" == createRepoResult) {
                console.log("创建仓库成功");
            } else {
                console.log("创建仓库失败, msg=" + createRepoResult);
                return false;
            }
        } else if (existRepo == 1) {
            console.log("仓库已存在");
        } else {
            console.log("获取仓库失败, msg=" + existRepo);
            return false;
        }
        const owner = await giteeUtils.getUser(this.token);
        if (owner === undefined || owner === null || owner.trim() === "") {
            console.log("获取用户信息失败，owner为空");
            return false;
        }
        //2.判断文件是否存在 
        const existFile = await giteeUtils.existFile(owner, this.repoName, this.fileName, this.token);
        // 不存在则创建
        if (existFile == 0) {
            const createRepoResult = await giteeUtils.createFile(this.token, owner, this.repoName, this.fileName);
            if (createRepoResult) {
                console.log("创建文件成功");
            } else {
                console.log("创建文件失败, msg=" + createRepoResult);
                return false;
            }
        } else if (existFile == 1) {
            console.log("文件已存在");
        } else {
            console.log("获取文件信息失败, msg=" + existRepo);
            return false;
        }
        return true;
    }

    /** 拉取远程数据 **/
    async pull() {
        const owner = await giteeUtils.getUser(this.token);
        if (!owner || owner === null || owner.trim() === "") {
            console.log("获取用户信息失败，owner为空");
            return "";
        }
        const result = giteeUtils.fetchFileContent(this.token, owner, this.repoName, this.fileName);
        if (result == null) {
            console.log("拉取远程数据失败");
            return "";
        }
        return result;
    }

    /** 从远程导入 **/
    async importBookmarksFromRemote(fileName = "") {
        const ck = await this.checkConfig();
        if (!ck) {
            return false;
        }
        if (fileName == "") {
            fileName = this.fileName;
        }
        const owner = await giteeUtils.getUser(this.token);

        const existFile = await giteeUtils.existFile(owner, this.repoName, fileName, this.token);
        if (existFile != 1) {
            notificationsUtils.showMsg("对应文件未找到，请先同步到远程。");
            return false;
        }
        const content = await giteeUtils.fetchFileContent(this.token, owner, this.repoName, fileName);
        if (!content || content === null || content.trim() === "") {
            notificationsUtils.showMsg("远程仓库无数据，请先同步到远程。");
            return false;
        }
        try {
            JSON.parse(content);
        } catch (e) {
            notificationsUtils.showMsg("远程数据格式不正确，非JSON格式，仓库名" + this.repoName + "文件名" + fileName);
            return false;
        }
        console.log("获取远程书签：" + content);

        await bookmarkUtils.removeAll();
        console.log("删除所有书签");
        console.log("开始导入");
        const importResult = await bookmarkUtils.importBookmarksFromJson(content);
        if (!importResult) {
            notificationsUtils.showMsg("导入失败");
        } else {
            notificationsUtils.showMsg("导入成功");
        }
        return importResult;

    }

    /** 检查配置 **/
    async checkConfig() {
        if (!this.token || this.token === null || this.token.trim() === "") {
            notificationsUtils.showMsg("Git令牌未配置");
            return false;
        }
        if (!this.repoName || this.repoName === null || this.repoName.trim() === "") {
            notificationsUtils.showMsg("仓库名称未配置");
            return false;
        }
        if (!this.fileName || this.fileName === null || this.fileName.trim() === "") {
            notificationsUtils.showMsg("文件名未配置");
            return false;
        }
        const owner = await giteeUtils.getUser(this.token);
        if (!owner || owner === null || owner.trim() === "") {
            notificationsUtils.showMsg("未获取到用户，请检查Git令牌是否正确");
            return false;
        }
        return true;
    }

    /** 同步到远程 **/
    async exportBookmarksToRemote() {
        const ck = await this.checkConfig();
        if (!ck) {
            return false;
        }
        const owner = await giteeUtils.getUser(this.token);
        const json = await bookmarkUtils.exportBookmarksToJson();
        try {
            JSON.parse(json);
        } catch (e) {
            console.error('JSON 解析失败:', e);
            console.error('json:' + json);
            notificationsUtils.showMsg("获取书签失败");
            return false;
        }
        const initResult = await this.initRemoteRepo();
        if (!initResult) {
            notificationsUtils.showMsg("初始化仓库失败");
            return false;
        }
        const oldJson = await giteeUtils.fetchFileContent(this.token, owner, this.repoName, this.fileName);
        if (oldJson === json) {
            notificationsUtils.showMsg("上传书签成功,无变化");
            return true;
        }
        const sha = await giteeUtils.getFileSha(owner, this.repoName, this.fileName, this.token);
        const updateResult = await giteeUtils.updateFile(this.token, owner, this.repoName, this.fileName, sha, json, '上传书签');
        if (!updateResult) {
            notificationsUtils.showMsg("上传书签失败");
            return false;
        }
        try {
            const now = new Date();
            const hisFileName = `his_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}.json`;
            await giteeUtils.createFile(this.token, owner, this.repoName, hisFileName, json);
        } catch (e) {
            console.debug('创建备份失败:', e);
        }

        let files = await giteeUtils.getLastHisList(owner, this.repoName, this.token);
        if (Array.isArray(files)) {
            for (const file of files) {
                giteeUtils.delFile(this.token, owner, this.repoName, file.name, file.sha);
            }
        }


        notificationsUtils.showMsg("上传书签成功");
        return true;
    }

    // 清除现有书签
    async removeAll() {
        await bookmarkUtils.removeAll();
    }

    async isautoSync(type, id) {
        const val = await chrome.storage.local.get(['autoSync']);
        if (val && val.autoSync) {
            return true;
        }
        return false;
    }

    async operationIsAuto(type, id) {
        const key1 = `${type}_${id}`;
        const val = await chrome.storage.local.get(key1);
        if (val && val[key1]) {
            return true;
        }
        return false;
    }

}
